# 二叉树的锯齿形层序遍历： https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/

# Definition for a binary tree node.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

        
from collections import deque

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> list:
        """
            第一种做法是：我采用广度优先遍历，定义栈
        """
        stack = deque()
        stack.append(root)
        rst = []
        sign = 0

        if not root: return []

        while len(stack) != 0:
            temp = []
            for i in range(len(stack)):
                node = stack.popleft()
                temp.append(node.val)
                if node.left:
                    stack.append(node.left)
                if node.right:
                    stack.append(node.right)
            
            # sign 判断是否需要逆序
            if sign == 0:
                rst.append(temp)
                sign = 1
            else:
                rst.append(temp[::-1])
                sign = 0
        
        return rst


